package com.wayne.testapp.activity;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.wayne.testapp.R;
import com.wayne.testapp.api.MovieService;
import com.wayne.testapp.api.RosettaApi;
import com.wayne.testapp.utils.CUtils;
import com.wayne.testapp.utils.FileSizeUtil;
import com.wayne.testapp.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by wayne on 2016/07/22.
 */
public class TestRxjavaActivity extends BaseActivity {
    AppCompatImageView iv_image;
    //    @InjectView(R.id.bt_rx_zip)
//    AppCompatButton bt_rx_zip;
    @InjectView(R.id.bt_rxbind1)
    AppCompatButton bt_rxbind1;
    @InjectView(R.id.bt_rxbind2)
    AppCompatButton bt_rxbind2;

    @InjectView(R.id.tv_show)
    AppCompatTextView tv_show;
    @InjectView(R.id.et_text)
    AppCompatEditText et_text;

    private static final String TAG = "TestRxjavaActivity";

    AppCompatTextView tv_text1;

    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_test_rxjava);
        ButterKnife.inject(this);
        initView();
        //点击事件
        RxView.clicks(bt_rxbind1).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                System.out.println("click！！！！！！！！！！！！！");
            }
        });
        //防止重复点击
        RxView.clicks(bt_rxbind2)
                .throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        count += 1;
                        CUtils.showToast(TestRxjavaActivity.this, count + "别急，3秒一发");
                    }
                });

        //
        et_text.setSingleLine();
        RxTextView.textChangeEvents(et_text).subscribe(new Subscriber<TextViewTextChangeEvent>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
                tv_show.setText(textViewTextChangeEvent.text());

            }
        });
        setView();
    }


    private void initView() {
        tv_text1 = (AppCompatTextView) findViewById(R.id.tv_text1);
        iv_image = (AppCompatImageView) findViewById(R.id.iv_image);
    }

    @OnClick({R.id.bt_rx_zip, R.id.bt_zip, R.id.bt_rx_retrofit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_rx_zip:
                Action1<File> onNext = new Action1<File>() {
                    @Override
                    public void call(File file) {
                        double size = FileSizeUtil.getFileOrFilesSize(file.getAbsolutePath(), FileSizeUtil.SIZETYPE_MB);
                        System.out.println("size== " + size + " mb");
                    }
                };
                Action0 onfinish = new Action0() {
                    @Override
                    public void call() {
                        System.out.println("打包完成");
                    }
                };
                Action1<Throwable> onError = new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        System.out.println("error== " + throwable.getMessage());
                    }
                };


                Observable.create(new Observable.OnSubscribe<File>() {
                    @Override
                    public void call(Subscriber<? super File> subscriber) {
//                        System.out.println(1/0+"");
                        File temp = rxzip();
                        subscriber.onNext(temp);
                        subscriber.onCompleted();
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<File>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                showDialog("正在打包");
                                System.out.println("打包开始啦");
                            }

                            @Override
                            public void onCompleted() {
                                System.out.println("打包完成");
                                closeDialog();
                            }

                            @Override
                            public void onError(Throwable e) {
                                System.out.println("error== " + e.getMessage());
                                closeDialog();
                            }

                            @Override
                            public void onNext(File file) {
                                double size = FileSizeUtil.getFileOrFilesSize(file.getAbsolutePath(), FileSizeUtil.SIZETYPE_MB);
                                System.out.println("size== " + size + " mb");
                            }
                        });
                break;
            case R.id.bt_zip:
//                System.out.println(1/0+"");
                File temp = zip();
                if (temp != null) {
                    double size = FileSizeUtil.getFileOrFilesSize(temp.getAbsolutePath(), FileSizeUtil.SIZETYPE_MB);
                    System.out.println("size== " + size + " mb");
                }
                break;
            case R.id.bt_rx_retrofit:
                requestByRx();
                break;
            default:
                break;
        }
    }

    private void requestByRx() {

        String baseUrl = "http://cbs-test.shenmajr.com/cbsapi/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        RosettaApi api = retrofit.create(RosettaApi.class);
        api.getSms("15000983434")
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {
                        System.out.println("nameC-----" + Thread.currentThread().getName());
                        Toast.makeText(TestRxjavaActivity.this, "取得数据", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println("nameE-----" + Thread.currentThread().getName());
                        tv_text1.setText("error == " + e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        System.out.println("nameN-----" + Thread.currentThread().getName());
                        tv_text1.setText("result == " + responseBody.toString());
                    }
                });

        ////////////
//        String baseUrl = "https://api.douban.com/v2/movie/";
//
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl(baseUrl)
//                .build();
//
//        MovieService movieService = retrofit.create(MovieService.class);
//
//        movieService.getTopMovie(0, 10)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<ResponseBody>() {
//                    @Override
//                    public void onCompleted() {
//                        Toast.makeText(TestRxjavaActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        tv_text1.setText(e.getMessage());
//                    }
//
//                    @Override
//                    public void onNext(ResponseBody movieEntity) {
//                        tv_text1.setText(movieEntity.toString());
//                    }
//                });
    }

    private File rxzip() {
        return zip();
    }

    private File zip() {
        try {
            String dir = CUtils.getSDPath() + File.separator + "tttt";
            File file = new File(dir);
            File[] tempList = file.listFiles();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");

            File result = FileUtils.compress2Zip(tempList, sdf.format(date) + ".zip");
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    private void setView() {
        Observable myObserv1 = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("Hello");
                subscriber.onNext("Hi");
                subscriber.onNext("Aloha");
                subscriber.onCompleted();
            }
        });

        Observable myObserv2 = Observable.just("hello", "hi", "aloha");
        List<String> list = new ArrayList<String>();
        list.add("boy");
        list.add("girl");
        Observable myObserv3 = Observable.from(list);
        Observable myObserv4 = Observable.just("haha", "hehe");

        myObserv1.subscribe(new Subscriber() {
            @Override
            public void onCompleted() {
                Log.i(TAG, "complete");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "error = " + e.getMessage());
            }

            @Override
            public void onNext(Object o) {
                Log.i(TAG, "str === " + o.toString());
            }
        });
        //显示图片


        final int res = R.mipmap.code_ios;
        Observable.create(new Observable.OnSubscribe<Drawable>() {
            @Override
            public void call(Subscriber<? super Drawable> subscriber) {
                Drawable d = ContextCompat.getDrawable(TestRxjavaActivity.this, res);
                subscriber.onNext(d);
                subscriber.onCompleted();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Drawable>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(TestRxjavaActivity.this, "Error!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(Drawable drawable) {
                        iv_image.setImageDrawable(drawable);
                    }
                });
    }

    AlertDialog dialog;

    public void showDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(msg);
        dialog = builder.show();
        dialog.setCanceledOnTouchOutside(false);
    }

    public void closeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}

